#include "transaction.h"
#include <Poco/Data/Session.h>
#include <Poco/Exception.h>

using namespace servercom;

Transaction::Transaction(Poco::Data::Session& session, bool auto_commit)
    : session_(session),
      auto_commit_(auto_commit),
      committed_(false),
      rolled_back_(false) {
    try {
        session_.begin();
    } catch (const Poco::Exception& e) {
        throw std::runtime_error("Failed to begin transaction: " + e.displayText());
    }
}

Transaction::~Transaction() {
    if (!committed_ && !rolled_back_ && auto_commit_) {
        try {
            commit();
        } catch (...) {
            // 忽略析构中的异常
        }
    } else if (!committed_ && !rolled_back_) {
        try {
            rollback();
        } catch (...) {
            // 忽略析构中的异常
        }
    }
}

void Transaction::commit() {
    if (committed_ || rolled_back_) {
        throw std::runtime_error("Transaction already completed");
    }

    try {
        session_.commit();
        committed_ = true;
    } catch (const Poco::Exception& e) {
        rolled_back_ = true;
        throw std::runtime_error("Failed to commit transaction: " + e.displayText());
    }
}

void Transaction::rollback() {
    if (committed_ || rolled_back_) {
        throw std::runtime_error("Transaction already completed");
    }

    try {
        session_.rollback();
        rolled_back_ = true;
    } catch (const Poco::Exception& e) {
        throw std::runtime_error("Failed to rollback transaction: " + e.displayText());
    }
}

bool Transaction::isActive() const {
    return !committed_ && !rolled_back_;
}